import sys
import pymongo
import json
from Config import config

class mongoUtil():
    def __init__(self, collection=None, host=config.mongo_host, port=config.mongo_port, username=config.mongo_username,
                 password=config.mongo_password, db=config.mongo_db):
        self.mongo_host = host
        self.mongo_port = port
        self.mongo_password = password
        self.mongo_username = username
        self.mongo_db = db
        self.mongo_col = collection

        self.mongo_conn()

    def mongo_conn(self):
        try:
            self.client = pymongo.MongoClient(self.mongo_host,self.mongo_port)
            if (self.mongo_username):
                self.client.security_detect.authenticate(
                    self.mongo_username,
                    self.mongo_password,
                    source=self.mongo_db
                )
            self.db = self.client[self.mongo_db]
            self.collection = self.db[self.mongo_col]
        except Exception,e:
            print("Error connecting to mongodb.%s"%e)

    def mongo_find(self,condition,find_one=False):
        if isinstance(condition, dict):
            if find_one:
                ret_data = self.collection.find_one(condition)
                return [ret_data] if ret_data else None
            else:
                return self.collection.find(condition)
        else:
            raise TypeError('input type must be dict.')
    def mongo_save(self, data):
        if isinstance(data, dict):
            self.collection.insert(data)
        else:
            raise TypeError('input type must be dict.')

    def mongo_update(self,fr,to):
        if isinstance(fr, dict) and isinstance(to, dict):
            self.collection.update(fr, {"$set": to})
        else:
            raise TypeError('input type must be dict.')
